/**
 * FileName: MyAop
 * Author:   xing.yang@vcg.com
 * Date:     2020/5/27 9:57
 * Description:
 */
package com.vcg.vdam.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.ExtendedServletRequestDataBinder;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponseWrapper;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class MyAop {

    @Pointcut("@annotation(com.vcg.vdam.aop.VdamAnnotation)")
    public void webLog(){}

    @Around("webLog()")
    public Object doAroud(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("进入到切面");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        System.out.println("URL : " + request.getRequestURL().toString());
        System.out.println("HTTP_METHOD : " + request.getMethod());
        System.out.println("IP : " + request.getRemoteAddr());

        Object[] objs = joinPoint.getArgs();
        String[] argNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames(); // 参数名
        Map<String, Object> paramMap = new HashMap<String, Object>();
        for (int i = 0; i < objs.length; i++) {
            if (!(objs[i] instanceof ExtendedServletRequestDataBinder) && !(objs[i] instanceof HttpServletResponseWrapper)
                    && !(objs[i] instanceof BeanPropertyBindingResult)
                    && !(objs[i] instanceof ServletRequest)
                    && !(objs[i] instanceof MultipartFile[])) {


                paramMap.put(argNames[i], objs[i]);
            }
        }

//        logger.info("入参:"+JSONObject.toJSONString(paramMap));
        Object obj = joinPoint.proceed();
        return obj;
    }
}
